package com.maxis;

import java.io.File;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeMap;

import org.json.simple.*;

import au.com.bytecode.opencsv.CSVWriter;

import com.classes.CaseOutlet;
import com.classes.Casemast;
import com.classes.CasemastFactory;
import com.classes.DBFactory;
import com.classes.OutletFactory;

public class MaxisMPOSStatus {
	private static final String CONFIG_FILE = "/maxis.properties";
	private static final java.util.Properties appCfg = new java.util.Properties();

	private String userGroup = "";
	private String delimiter = "";
	private String mapStatusPath = "";
	private String[] externalCodeNoExport = new String[] {};
	private String[] externalCodeExportOnce = new String[] {};

	public static void main(String[] args) {
		try {
			InputStream stream = MaxisMPOS.class.getResourceAsStream(CONFIG_FILE);
			if (stream != null){
				appCfg.load(stream);
			} else {
				System.out.println("MaxisMPOS Input Stream is NULL");
			}

		} catch (Exception e) {
			System.err.println("MaxisMPOS Error loading file " + CONFIG_FILE);
			System.err.println(e.getMessage());
			e.printStackTrace();
		}

		MaxisMPOSStatus fw = new MaxisMPOSStatus();

		fw.userGroup = appCfg.getProperty("user_group");
		fw.delimiter = appCfg.getProperty("file_delimiter");
		fw.mapStatusPath = appCfg.getProperty("MapStatusPath");
		
		String configStr = appCfg.getProperty("external_code_no_export");
		if(configStr.equals("") == false){
			fw.externalCodeNoExport = configStr.split(",");
		}
		
		configStr = appCfg.getProperty("external_code_export_once");
		if(configStr.equals("") == false){
			fw.externalCodeExportOnce = configStr.split(",");
		}
		
		fw.startWork();
	}

	public void startWork(){
		boolean ok = DBFactory.connect();
		if(ok == false){
			System.out.println(DBFactory.getMessage());
			return;
		}

		
		ArrayList<Casemast> cArr = CasemastFactory.getActiveCasemasts(this.userGroup, new TreeMap<String, String>());
		if(cArr == null){
			System.out.println(CasemastFactory.getMessage());
			return;
		}

		
		try {
			String csvStatusFilePath = this.createStatusFolder() + this.statusFileName();
			CSVWriter writer = CSVFactory.getWriter(csvStatusFilePath, this.delimiter.charAt(0));
			
			
			String sql = "update casemast set c_export_ext_code = ?"
						+ "where c_id = ?";
			
			PreparedStatement statement = DBFactory.getConnection().prepareStatement(sql);
			
			
			try {
				System.out.println("Exporting applications #" + cArr.size());
				
				OutletFactory o = new OutletFactory();
	
				for(Casemast c : cArr) {
					System.out.println("Application Reference #" + c.getReferenceNo());
					
					ArrayList<CaseOutlet> c_outlets = o.getCaseOutlets((int) c.getId());
					if(c_outlets == null){
						System.out.println(o.getMessage());
						return;
					}
	
					if(c_outlets.size() > 0) {
						String mdr = c_outlets.get(0).getOutlet().getMDRRate();
						JSONObject mdr_obj = new JSONObject();
	
						if(mdr.length() > 0) {
							mdr_obj = (JSONObject) JSONValue.parse(mdr);
						}
	
						
						String maxisCode = c.getExternalCode();
						int maxisCodeInt = 0;
						
						if(maxisCode.equals("") == false){
							maxisCodeInt = Integer.parseInt(maxisCode);
						}
						
						if(maxisCode.equals("") || this.existInArray(maxisCode, this.externalCodeNoExport)){
							System.out.println("*******maxisCode=" + maxisCode);
							continue;
						}
						
						if(this.existInArray(maxisCode, this.externalCodeExportOnce)) {
							if(c.getExportedExternalCode().equals(maxisCode)) {
								continue;
							}
						}
						
						
						String[] data = new String[8];
	
						if(maxisCode.equals("0101")){
							data[0] = c.getExternalRefNo();
						} else {
							data[0] = "";
						}
	
						data[1] = c.getReferenceNo();
						data[2] = maxisCode;
						data[3] = "";
						
						if(mdr_obj.get("14") != null) {
							if(maxisCodeInt >= 204){
								data[3] = mdr_obj.get("14").toString();
							}
						}
	
						data[4] = c.getExternalRemark();
						data[5] = c.getDocumentChecklist();
						data[6] = "";
						data[7] = "";
	
						writer.writeNext(data);
						
						
						statement.setString(1, maxisCode);
						statement.setInt(2, (int) c.getId());
						
						statement.execute();
						
					}
					else {
						System.out.println("*******Outlets array is empty.");
					}

				
				}
				
			} finally {
				writer.close();
				statement.close();
			}
			
		} catch (Exception e){
			e.printStackTrace();
		}

		DBFactory.close();
	}
	
	private boolean existInArray(String str, String[] arr) {
		for(String s : arr) {
			if(s.equals(str)) {
				return true;
			}
		}
		
		return false;
	}

	private String statusFileName(){
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");

		return "mbb_" + sdf.format(d) + ".txt";
	}

	private String createStatusFolder(){
		   Date dNow = new Date();
		   SimpleDateFormat dformat = new SimpleDateFormat ("yyyy.MM.dd");
		   //File resfolder = new File(this.mapStatusPath + dformat.format(dNow) + "/");
		   File resfolder = new File(this.mapStatusPath + "/");		
		   
		   boolean b = false;

		   if (!resfolder.exists()) {
			   b = resfolder.mkdirs();
		   }

		   //return this.mapStatusPath + dformat.format(dNow) + "/";
		   return this.mapStatusPath + "/";
	}
}
